package algorthm.sqlparser;


import java.util.Objects;

import static algorthm.sqlparser.SqlNodeType.*;

/**
 * @className: SQLParser
 * @Description:
 * @Author: wangyifei
 * @Date: 2024/3/23 19:51
 */
public class SQLParser {
    public static void main(String[] args) {
       String sql = "select * from user where id = 1 and name = 'wangyifei'";
        SqlNode sqlNode = process1(sql);
        StringBuilder sb = new StringBuilder();
        forTree(sqlNode , sb);
        System.out.println(sb.toString());
    }
    public static SqlNode process1(String sql) {
        int index = sql.lastIndexOf(SELECT.getType());
        SqlNode node = null ;
        if(-1 != index){
            node = new SqlNode(SELECT);
            node.left = new SqlNode(FIELD);
            node.left.cnt = sql.substring(SELECT.getType().length() ,sql.indexOf(FROM.getType()));
            node.right = process1(sql.substring(SELECT.getType().length()));
            return node ;
        }
        index = sql.lastIndexOf(FROM.getType());
        if(-1 != index){
            node = new SqlNode(FROM);
            node.left = new SqlNode(TABLE);
            node.left.cnt = sql.substring(index + FROM.getType().length() , sql.indexOf(WHERE.getType()));
            node.right = process1(sql.substring(index + FROM.getType().length() + 1));
            return node;
        }
        index = sql.lastIndexOf(WHERE.getType());
        if(-1 != index){
            node = new SqlNode(WHERE);
            node.left = new SqlNode(OPERATOR);
            node.left.cnt = sql.substring(index + WHERE.getType().length());
        }
        return node;
     }
     public static void forTree(SqlNode node , StringBuilder sb){
         if(node.type.equals(FIELD)){
             sb.append(node.cnt);
             return;
         }else if(node.type.equals(SELECT)){
             sb.append("选择字段为:");
             if(Objects.nonNull(node.left)){
                 forTree(node.left , sb);
             }
             if(Objects.nonNull(node.right)){
                 forTree(node.right , sb);
             }
         }
         if(node.type.equals(TABLE)){
             sb.append(node.cnt);
             return;
         }else if(node.type.equals(FROM)){
             sb.append( "从表:");
             if(Objects.nonNull(node.left)){
                forTree(node.left , sb);
             }
             if(Objects.nonNull(node.right)){
                forTree(node.right , sb);
             }
         }else if(node.type.equals(WHERE)){
             sb.append("条件为:" );
             if(Objects.nonNull(node.left)){
                forTree(node.left ,sb);
             }
         }else if(node.type.equals(OPERATOR)){
             sb.append("条件为:" + node.cnt);
         }
     }
}

